package com.discuss.community.aspect;

import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.Date;

@Component
@Slf4j
@Aspect
public class ServiceLogAspect {
    @Pointcut("execution(* com.discuss.community.service.*.*(..))")
    public void pointcut() {}

    @Before("pointcut()")
    public void before(JoinPoint joinPoint) {
        ServletRequestAttributes requestAttributes =
                (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if(requestAttributes == null) {
            log.info("用户触发事件");
            return;
        }
        HttpServletRequest request = requestAttributes.getRequest();
        // 获取请求的IP地址
        String ip = request.getRemoteHost();
        // 创建时间
        String now = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
        // 获取访问方法的所属全类名
        String declaringTypeName = joinPoint.getSignature().getDeclaringTypeName();
        // 获取访问方法名
        String name = joinPoint.getSignature().getName();
        // 构建访问方法全名
        String target = declaringTypeName + "." + name;

        // 打印日志
        log.info(String.format("用户[%s],在[%s],访问了[%s].", ip, now, target));
    }
}
